﻿using Microsoft.OpenApi.Models;

namespace DFGJ.WMS_PDA.WebAPI.Extensions
{
    /// <summary>
    /// Swagger扩展
    /// </summary>
    public static class SwaggerExtend
    {
        /// <summary>
        /// 注入自定义Swagger   
        /// </summary>
        /// <param name="builder"></param>
        public static void AddSwaggerSetUp(this WebApplicationBuilder builder)
        {
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen(option =>
            {
                typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
            {
                option.SwaggerDoc(version, new OpenApiInfo()
                {
                    Title = $"仓储管理系统接口文档",
                    Version = version,
                    Description = $"通用版本的CoreApi版本{version}"
                });
            });

                // xml文档绝对路径 
                var file = Path.Combine(AppContext.BaseDirectory, "DFGJ.WMS_PDA.WebAPI.xml");
                // true : 显示控制器层注释
                option.IncludeXmlComments(file, true);
                // 对action的名称进行排序。
                option.OrderActionsBy(o => o.RelativePath);


                #region 开启Swagger认证
                option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {

                    Description = "在下框中输入请求头中需要添加Jwt授权Token：Bearer Token",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });

                option.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme,
                                Id = "Bearer"
                            }
                        },
                        new string[] { }
                    }
                });
                #endregion
            });


        }

        /// <summary>
        /// Swagger中间件 
        /// </summary>
        /// <param name="app"></param>
        public static void UseSwaggerExtend(this WebApplication app)
        {
            if (app.Environment.IsDevelopment())
            {

            }  
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                foreach (string version in typeof(ApiVersions).GetEnumNames())
                {
                    c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"东方国际WMS第【{version}】版本");
                }
            });
        }

    }
    public enum ApiVersions
    {
        V1,
        V2
    }

}
